package com.example.smartall.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.smartall.R;
import com.example.smartall.adapter.NewsListAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.LoadedDialog;
import com.example.smartall.entity.NewsBean;
import com.example.smartall.entity.NewsCommendBean;
import com.example.smartall.entity.NewsDetailsBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.utils.Constant;
import com.example.smartall.utils.SPUtils;
import com.example.smartall.view.SListView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 新闻详细详细
 * 包含新闻详细 标题栏 查看评论 评论 新闻推荐
 *
 * 2022/1/19 获取新闻评论列表 评论 有误
 */
public class NewsDetailsActivity extends BaseActivity {

    private int id;
    private String title;
    private ImageView imBack;
    private TextView tvTitle;
    private WebView webView;
    private Button btComment;
    private SListView lvRecommend;
    private EditText etComment;

    private NewsDetailsBean.DataBean bean;
    private List<NewsBean.RowsBean> newsBeans;
    private NewsListAdapter newsListAdapter;

    private int pageNum = 1;
    private int count = -1;
    private boolean isLoadCommend = false;

    private MHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_details);

        id = getIntent().getIntExtra("id",-1);
        title = getIntent().getStringExtra("title");
        if (id < 0){
            return;
        }
        handler = new MHandler();

        init();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
        getRecommend();
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void init() {
        newsBeans = new ArrayList<>();
        imBack = (ImageView) findViewById(R.id.im_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        webView = (WebView) findViewById(R.id.webView);
        btComment = (Button) findViewById(R.id.bt_comment);
        lvRecommend = (SListView) findViewById(R.id.lv_recommend);
        etComment = (EditText) findViewById(R.id.et_comment);

        tvTitle.setText(title);
        webView.getSettings().setJavaScriptEnabled(true);
        imBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewsDetailsActivity.this.finish();
            }
        });
    }

    @Override
    public void initEvent() {
        etComment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND){
                    sendComment();
                }
                return false;
            }
        });

        btComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLoadCommend){
                    if (pageNum * 12 >= count){
                        showToast("没有更多数据！");
                    }else {
                        getCommend(pageNum);
                    }
                }else {
                    getCommend(pageNum);
                }
            }
        });
    }

    private void initData() {
        newsListAdapter = new NewsListAdapter(NewsDetailsActivity.this,newsBeans);
        lvRecommend.setAdapter(newsListAdapter);
    }

    private void getRecommend(){
        Api.config(ApiConfig.NEWS_URL,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsBean bean = new Gson().fromJson(res,NewsBean.class);
                newsBeans = bean.getRows();
                handler.sendEmptyMessage(0x02);
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        }, "?hot=Y");
    }

    /** 回来瞄一眼，突然看懂了报错
     * "msg": "\r\n### Error updating database.  Cause: java.sql.SQLSyntaxErrorException:
     *  Unknown column 'content' in 'field list'
     *  \r\n### The error may exist in URL [jar:file:/D:/zhcsnew/server-v2/ljxl-admin.jar!/BOOT-INF/lib/sc-common-3.3.0.jar!/mapper/news/ComNewsCommentMapper.xml]
     *  \r\n### The error may involve com.ljxl.sc.common.mapper.ComNewsCommentMapper.insertComNewsComment-Inline
     *  \r\n### The error occurred while setting parameters
     *  \r\n### SQL: insert into com_news_comment   (app_type,news_id, content,comment_date,user_id,like_num )   values ( ?,             ?,             ?,             ?,             ?,             ? )
     *  \r\n### Cause: java.sql.SQLSyntaxErrorException: Unknown column 'content' in 'field list'\n; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Unknown column 'content' in 'field list'",
     *   "code": 500
     */
    private void sendComment() {
        HashMap<String,Object> params = new HashMap<>();
        params.put("newsId",id);
//        曾经
//        params.put("content",etComment.getText().toString());
//        现在
        params.put(" content",etComment.getText().toString());
//        妙啊
        Api.config(ApiConfig.SEND_COMMEND,params).postRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                if (res.contains("200")){
                    showToastSync("评论成功");
                    etComment.setText("");
                }else{
                    showToastSync(res);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("评论失败,检查网络");
                Log.e("发送评论",e.toString());
            }
        }, SPUtils.config(NewsDetailsActivity.this, Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN));
    }

    private void getData(){
        Api.config(ApiConfig.NEWS_DETAILS,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsDetailsBean newsDetailsBean = new Gson().fromJson(res,NewsDetailsBean.class);
                if (newsDetailsBean.getCode() == 200) {
                    bean = newsDetailsBean.getData();
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        }, id+"");
    }

    //TODO
    private void getCommend(int pageNum){
        Api.config(ApiConfig.NEWS_COMMEND,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsCommendBean bean = new Gson().fromJson(res,NewsCommendBean.class);
            }

            @Override
            public void onFailure(Exception e) {

            }
        },"newsId="+id+"pageNum="+pageNum+"pageSize=12");
    }

    class MHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x01:
                    webView.loadDataWithBaseURL(null,bean.getContent(),null,"utf-8",null);
                    break;
                case 0x02:
                    initData();
                    break;
            }
        }
    }

}